package com.atguigu.gmall0218.payment.controller;

import com.atguigu.gmall0218.bean.enums.PayOrg;
import com.atguigu.gmall0218.payment.PayStrategy.PayStrategyContext;
import com.atguigu.gmall0218.payment.constant.ExceptCodeConstants;
import com.atguigu.gmall0218.payment.exception.BusinessException;
import com.atguigu.gmall0218.payment.module.req.PaymentReqParam;
import com.atguigu.gmall0218.payment.service.impl.PayCenterCombSVImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <pre>
 *    @author  : liquid
 *    email   : xiaokui.li@guigu.com
 *    desc    : 支付入口
 *    version : v1.1
 * </pre>
 */
@Controller
@Slf4j
public class PayController {

    @Autowired
    private PayCenterCombSVImpl payCenterCombSV;

    @RequestMapping("pay/submit")
    public ModelAndView paySubmit(HttpServletRequest request, PaymentReqParam paymentReqParam){
        //获取支付方式
        String orderId = request.getParameter("orderId");
        String payOrgCode = request.getParameter("payOrgCode");
        int i = Integer.parseInt(payOrgCode);
        String payOrgName = PayOrg.getName(i);
        if (Objects.isNull(payOrgName)){
            String message = "获取不到该支付类型的： " + payOrgCode + "配置管理类实例，请查看配置或暂不支持此支付方式";
            log.error(message);
            throw new BusinessException("0001",message);
        }
        //创建支付记录和支付日志
        payCenterCombSV.createPaymentInfo(orderId,payOrgName);
        // 获取对应的支付类型url
        String payAction = PayStrategyContext.getPayAction(payOrgName);//alipayConfig
        ///alipay/webPayment/alipayapi
        log.info("跳转支付action: " + payAction);
        if(Objects.isNull(payAction)) {
            log.error("支付遇到问题,跳转不到对应的支付网页进行支付操作！");
            throw new BusinessException(ExceptCodeConstants.NO_PAY_STYLE, "支付遇到问题,跳转不到对应的支付网页进行支付操作！");
        }
        ModelAndView mv = new ModelAndView();
        //服务器内部转发，地址栏不变
        mv.setViewName("forward:" + payAction);
        return mv;
    }
}
